#include <iostream>
#include <fstream>
#include "contacts.pb.h"

void addPeopleInfo(s_contacts::PeopleInfo *people)
{
	std::cout << "-------------新增联系人------------" << std::endl;
	std::cout << "请输入联系人姓名：";
	std::string name;
	getline(std::cin, name);
	people->set_name(name);
	// std::cout << "请输入联系人年龄：";
	// int age;
	// std::cin >> age;
	// people->set_age(age);

	std::cout << "请输入联系人生日: ";
	int birthday;
	std::cin >> birthday;
	people->set_birthday(birthday);

	std::cin.ignore(256, '\n'); // 如果不清理，缓冲区中还有 \n 后续getline(std::cin,number);就直接把 \n 输入给number，就触发了break
	for (int i = 1;; i++)
	{
		std::cout << "请输入联系人电话" << i << "(按回车就退出)：";
		std::string number;
		getline(std::cin, number);
		if (number.empty())
		{
			break;
		}
		s_contacts::PeopleInfo_Phone *phone = people->add_phone();
		phone->set_number(number);
	}
	std::cout << "-----------新增联系人成功----------" << std::endl;
}

int main()
{
	s_contacts::Contacts contach;
	// 如果本地有信息先读取本地信息进行反序列化
	std::fstream input("../contach.bin", std::ios::in | std::ios::binary);
	if (!input.is_open())
	{
		std::cout << " input open error , create contach.bin" << std::endl;
	}
	else if (!contach.ParseFromIstream(&input))
	{
		std::cout << " Parse error " << std::endl;
		input.close();
		return -1;
	}
	// 添加联系人
	addPeopleInfo(contach.add_contacts());
	// 把联系人写入本地信息

	std::fstream output("../contach.bin", std::ios::out | std::ios::trunc | std::ios::binary);
	if (!contach.SerializeToOstream(&output))
	{
		std::cout << " serialize error " << std::endl;
		input.close();
		return -1;
	}

	std::cout << "write succeed" << std::endl;
	input.close();
	output.close();
	return 0;
}